package models;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

import entities.Domain;

public class DomainModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "domain_";
	
	private static DomainModel instance = null;
	
	public static DomainModel getInstance() {
		if (instance == null) {
			instance = new DomainModel();
		}
		
		return instance;
	}
	
	private DomainModel() {
		try {
			ObjectifyService.register(Domain.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		/*try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }*/
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public Domain get(String domainName) {
		Domain domain = new Domain();
		
		try {
			domain = ofy.get(new Key<Domain>(Domain.class, domainName));
		} catch (Exception e) {
			domain = null;
		}
		return domain;
	}
	
	public void insert(Domain domain) {
		ofy.put(domain);
	}
	
	public void delete(Domain domain) {
		ofy.delete(domain);
	}

	public List<Domain> getByListId(List<String> ids) {
		List<Domain> domains = new ArrayList<Domain>();
		Domain domain = null;
		for (int i = 0; i < ids.size(); i++) {
			domain = get(ids.get(i));
			if (domain != null) {
				domains.add(domain);
			}
		}
		
		return domains;
	}
	
}
